<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <template #title>
        <div v-html="highlight(text)"></div>
      </template>
    </van-cell>
  </div>
</template>
<script>
import { getSearchSuggestions } from "@/api/serach.js";
import { debounce } from "lodash";
export default {
  name: "searchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
      htmlStr: "Hello <span >World</span>",
    };
  },
  computed: {},
  watch: {
    searchText: {
      // 当 searchText 发生改变的时候就会调用 handler 方法
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value);
      }, 200),
      // 该回调将会在侦听开始以后被立即调用
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        this.suggestions = data.data.options;
      } catch (error) {
        this.$toast("获取数据失败, 请稍后重试");
      }
    },
    highlight(text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`;
      const reg = new RegExp(this.searchText, "gi");
      return text.replace(reg, highlightStr);
 
    },
  },
};
</script>
<style scoped lang='less'>
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>